package cn.clx.ymcc.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign的请求参数公共设置
 *   给Feign调用携带上token
 */
@Component
public class TokenForwordFeignInterceptor implements RequestInterceptor {

    //请求头中的token
    private final String AUTHORIZATION_HEADER = "Authorization";


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.从当前请求头中获取token  Authorization
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(AUTHORIZATION_HEADER);
        if(StringUtils.hasLength(token)){
            //2.将token 添加到Feign的请求（RequestTemplate）头中
            requestTemplate.header(AUTHORIZATION_HEADER,token);
        }

    }
}